package android.slc.helper;

import android.slc.utils.SlcThreadUtils;
import cn.hutool.core.thread.ThreadUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * CompletableFuture 辅助工具
 *
 * @author slc
 * @date 2024/6/25
 **/
public class CompletableFutureHelper<U> {

    private final Executor executor;

    private final List<CompletableFuture<U>> completableFutureList = new ArrayList<>();

    public CompletableFutureHelper() {
        this(SlcThreadUtils.getIoPool());
    }

    public CompletableFutureHelper(Executor executor) {
        this.executor = executor;
    }

    public Executor getExecutor() {
        return executor;
    }

    public CompletableFuture<U> create() {
        CompletableFuture<U> completableFuture = new CompletableFuture<>();
        return completableFuture;
    }

    public CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        CompletableFuture<U> completableFuture;
        if (executor != null) {
            completableFuture = CompletableFuture.supplyAsync(supplier, executor);
        } else {
            completableFuture = CompletableFuture.supplyAsync(supplier);
        }
        completableFutureList.add(completableFuture);
        return completableFuture;
    }

    /**
     * 获取所有数据
     *
     * @return
     */
    public List<U> getAllResult() {
        List<U> dataList = new ArrayList<>();
        completableFutureList.forEach(new Consumer<CompletableFuture<U>>() {
            @Override
            public void accept(CompletableFuture<U> completableFuture) {
                try {
                    U data = completableFuture.get();
                    dataList.add(data);
                } catch (InterruptedException | ExecutionException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return dataList;
    }
}
